//
//  WmcFeedbackVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/1.
//

import YPKeyboardManager
import JXPhotoBrowser
import UIKit
import YPBedrock

// MARK: - 扩展WmcFeedbackVC + WmcNavigatorProtocol

extension WmcFeedbackVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.feedback]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcFeedbackVM()

        if let viewModel = parms.context as? WmcFeedbackVM {
            vm = viewModel
        }

        let vc = WmcFeedbackVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcFeedbackVC + WmcVMProtocol

extension WmcFeedbackVC: WmcVMProtocol {
    typealias VMType = WmcFeedbackVM
}

// MARK: - [WmcFeedbackVC]

class WmcFeedbackVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        viewModel.loadList()
        loadData()
    }

    // Internal

    lazy var tableView: UITableView = {
        let tableView = UITableView.YP.Create(style: .grouped, delegate: self, dataSource: self, registers: [
            YPRegister(WmcFeedbackCell.self),
            YPRegister(WmcFeedbackInputCell.self),
        ])
        tableView.backgroundColor = .wmc_grayH19_F5F5F5
        tableView.tableFooterView = tableFooterView
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.shouldIgnoreScrollingAdjustment = true
        tableView.shouldRestoreScrollViewContentOffset = true
        return tableView
    }()

    lazy var tableFooterView: WmcFeedbackFooterView = {
        let view = WmcFeedbackFooterView(frame: CGRect(x: 0, y: 0,
                                                       width: Wmc_screenWidth,
                                                       height: 500.wmc_autoVer))
        view.submitClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.submit()
        }
        return view
    }()

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "意见反馈"

        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    // Private

    private func loadData() {
        WmcHudManager.loading()
        viewModel.fetchFeedback().subscribe { [weak self] model in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            weakSelf.tableFooterView.bindModel(model)
        } onError: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.tableFooterView.bindModel(nil)
        }.disposed(by: rx.disposeBag)
    }

    private func pushImageBrowse(images: [UIImage], scrollTo index: Int) {
        let browser = JXPhotoBrowser()
        browser.numberOfItems = {
            return images.count
        }

        browser.reloadCellAtIndex = { context in
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            let image = images[context.index]
            browserCell?.imageView.image = image

            browserCell?.yp.addLongPressGesture { gestrue in
                guard gestrue.state == .began else { return }

                let alert = WmcAlertView()
                alert.title = "提示"
                alert.msg = "是否保存图片？"
                alert.style = .custom(confirmTitle: "保存到相册", cancelTitle: "取消")
                alert.confirmBlock = {
                    let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                    if photoAlbumStatus.info.isAvailable {
                        UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.saveImage(_:didFinishSaving:contextInfo:)), nil)
                    } else {
                        WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                    }
                }
                alert.show()
            }
        }

        browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
        browser.pageIndex = index
        browser.show()
    }

    @objc
    private func saveImage(_ image: UIImage, didFinishSaving error: Error?, contextInfo: AnyObject) {
        if error != nil {
            WmcHudManager.toast("保存失败")
        } else {
            WmcHudManager.toast("保存成功")
        }
    }
}

// MARK: - UITableViewDelegate

extension WmcFeedbackVC: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.endEditing(true)
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let type = WmcFeedbackVM.QuestionType.allCases
            let typeNames = type.map { $0.rawValue }

            let sheet = WmcSheetView()
            sheet.title = "请选择问题类型"
            sheet.items = typeNames
            sheet.show()
            sheet.didSelectIndexBlock = { [weak self] index in
                guard let weakSelf = self else { return }
                guard index < type.count, weakSelf.viewModel.dataList.count > 0 else { return }
                let text = typeNames[index]
                weakSelf.viewModel.questionType = type[index]
                var temp = weakSelf.viewModel.dataList
                guard let item = temp.yp.object(at: 0)?.yp.object(at: 0) else { return }
                item.content = text
                temp[0] = [item]
                weakSelf.viewModel.dataList = temp
                weakSelf.tableView.reloadData()
            }
        }
    }
}

// MARK: - UITableViewDataSource

extension WmcFeedbackVC: UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return .YP.Min
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.dataList.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let group = viewModel.dataList.yp.object(at: section) {
            return group.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let group = viewModel.dataList.yp.object(at: indexPath.section),
           let item = group.yp.object(at: indexPath.row)
        {
            if item.style == .input {
                return UITableView.automaticDimension
            } else {
                return item.rowHeight
            }
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var _cell: WmcBaseTableCell = .init()
        if let group = viewModel.dataList.yp.object(at: indexPath.section),
           let model = group.yp.object(at: indexPath.row)
        {
            if model.style == .input {
                let cell: WmcFeedbackInputCell = tableView.yp.dequeueReusableCell()
                cell.tableView = tableView
                cell.indexPath = indexPath
                cell.configModel(model)
                cell.textDidChange = { [weak self] text in
                    guard let weakSelf = self else { return }
                    if indexPath.section == 1, indexPath.row == 0 {
                        weakSelf.viewModel.describe = text
                    }
                }
                cell.imagesDidChange = { list in
                    if indexPath.section == 1, indexPath.row == 0 {
                        self.viewModel.images = list
                    }
                }
                cell.clickImage = { index in
                    if index < self.viewModel.images.count {
                        self.pushImageBrowse(images: self.viewModel.images, scrollTo: index)
                    }
                }
                _cell = cell
            } else {
                let cell: WmcFeedbackCell = tableView.yp.dequeueReusableCell()
                cell.configModel(model)
                cell.textDidChange = { text in
                    if indexPath.section == 2, indexPath.row == 0 {
                        self.viewModel.contact = text
                    }
                }
                _cell = cell
            }
        }
        return _cell
    }
}
